import { useReducer, useEffect, useCallback } from 'react';
import { todoReducer, initialState } from '../reducers/todoReducer';

export function useTodoManager() {
  const [state, dispatch] = useReducer(todoReducer, initialState);
  
  // 使用 useEffect 保存到 localStorage
  useEffect(() => {
    localStorage.setItem('todos', JSON.stringify(state.todos));
  }, [state.todos]);
  
  // 使用 useCallback 优化函数引用
  const addTodo = useCallback((text) => {
    if (text.trim() !== '') {
      dispatch({ type: 'ADD_TODO', payload: text });
    }
  }, []);
  
  const toggleTodo = useCallback((id) => {
    dispatch({ type: 'TOGGLE_TODO', payload: id });
  }, []);
  
  const deleteTodo = useCallback((id) => {
    dispatch({ type: 'DELETE_TODO', payload: id });
  }, []);
  
  const setFilter = useCallback((filter) => {
    dispatch({ type: 'SET_FILTER', payload: filter });
  }, []);
  
  const editTodo = useCallback((id, text) => {
    console.log(`Editing todo ${id} with text: ${text}`);
    if (text.trim() !== '') {
      dispatch({ type: 'EDIT_TODO', payload: { id, text } });
    }
  }, []);
  
  // 根据过滤条件获取待办事项
  const filteredTodos = state.todos.filter(todo => {
    if (state.filter === 'active') return !todo.completed;
    if (state.filter === 'completed') return todo.completed;
    return true; // 'all'
  });
  
  return {
    todos: filteredTodos,
    filter: state.filter,
    addTodo,
    toggleTodo,
    deleteTodo,
    setFilter,
    editTodo
  };
} 